function formatTime(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()

  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()


  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}
function wxPromisify(fn) {
  return function (obj = {}) {
    return new Promise((resolve, reject) => {
      obj.success = function (res) {
        resolve(res)
      }

      obj.fail = function (res) {
        reject(res)
      }

      fn(obj)
    })
  }
}
//授权验证
function authori(url) {
  // 查看是否授权
  wx.getSetting({
    success: function (res) {
      if (!res.authSetting['scope.userInfo']) {// 未授权
        var s = "";
        if (url.path) {//url参数判断
          if (JSON.stringify(url.query) != "{}") {
            let query = url.query;
            s = JSON.stringify(query)
            url = url.path
          } else {
            url = url.path;
          }
        } else {
          url = "/pages/index/index"
        }
        wx.redirectTo({
          url: "/pages/authori/index?back=" + url + "&query=" + s,
        })
      }
    }
  })
}
//授权验证(登陆规范修改后的)
function isAccredit(cb) {
  let isAccredit = false;
  // 查看是否授权
  wx.getSetting({
    success: function (res) {
      console.log("授权验证");
      if (res.authSetting['scope.userInfo']) {// 已授权
        isAccredit = true;
      }
      cb(isAccredit);
    }
  })
}
/**
   * 发送表单id
   * 参数formid
   */
function addFormIdMsg(formid) {
  var app = getApp();
  wx.request({
    url: app.globalData.host + '/api/WeApp/AddFormId?uid=' + app.globalData.userInfo.Uid + '&formId=' + formid,
    success: function (res) {
      if (res.data.Code == 0) { }
    },
  })
}

// 订阅消息弹窗
function subscribe() {
  var app = getApp();
  console.log("消息订阅");
  wx.request({
    url: app.globalData.host + '/api/weapp/GetTemplateId?storeAppId=' + app.globalData.storeAppId,
    success: function (res) {
      console.log('模板Id集合', res.data.Data.tmplIds);
      let tmplIds = res.data.Data.tmplIds;
      let newTemplate = [];
      if (tmplIds.length > 3) {
        for (let i = 0; i < 3; i++) {
          newTemplate.push(tmplIds[i]);
        }
      } else {
        newTemplate = tmplIds;
      }
      console.log("筛选后模板id集合", newTemplate);
      if (newTemplate.length > 0){
        wx.requestSubscribeMessage({
          tmplIds: newTemplate,
          success(res) {
            console.log('订阅成功', res);
          },
          fail(res) {
            console.log('订阅失败', res);
          },
          complete(res) {
            console.log('订阅完成', res);
          }
        })
      }
    }
  })
}

// 订阅消息兼容判断
function subscribe2() {
  var app = getApp();
  console.log("消息订阅2");
  wx.request({
    url: app.globalData.host + '/api/weapp/GetTemplateId?storeAppId=' + app.globalData.storeAppId,
    success: function (res) {
      console.log('模板Id集合2', res.data.Data.tmplIds);
      let tmplIds = res.data.Data.tmplIds;
      let newTemplate = [];
      if (tmplIds.length > 3) {
        for (let i = 0; i < 3; i++) {
          newTemplate.push(tmplIds[i]);
        }
      } else {
        newTemplate = tmplIds;
      }
      const version = wx.getSystemInfoSync().SDKVersion;
      if (compareVersion(version, '2.8.2') >= 0) {
        if (newTemplate.length > 0){
          wx.requestSubscribeMessage({
            tmplIds: newTemplate,
            success(res) {
              console.log('订阅成功', res);
            },
            fail(res) {
              console.log('订阅失败', res);
            },
            complete(res) {
              console.log('订阅完成', res);
            }
          })
        }
      } else {
        // 如果希望用户在最新版本的客户端上体验您的小程序，可以这样子提示
        wx.showModal({
          title: '提示',
          content: '当前微信版本过低，无法使用订阅消息功能，请升级到最新微信版本后重试。'
        })
      }
    }
  })
}

function compareVersion(v1, v2) {
  v1 = v1.split('.')
  v2 = v2.split('.')
  const len = Math.max(v1.length, v2.length)
  while (v1.length < len) {
    v1.push('0')
  }
  while (v2.length < len) {
    v2.push('0')
  }
  for (let i = 0; i < len; i++) {
    const num1 = parseInt(v1[i])
    const num2 = parseInt(v2[i])

    if (num1 > num2) {
      return 1
    } else if (num1 < num2) {
      return -1
    }
  }
  return 0
}

module.exports = {
  wxPromisify: wxPromisify,
  formatTime: formatTime,
  authori: authori,
  addFormIdMsg: addFormIdMsg,
  isAccredit: isAccredit,
  subscribe: subscribe,
  subscribe2: subscribe2
}
